<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html lang="en">
<head>
    <title>Title</title>
</head>
<body>
<form id="formOpe">
    <input type="hidden" name="id"> <br>
    <input type="text" name="userName" placeholder="用户姓名"> <br>
    <input type="text" name="password" placeholder="密码"> <br>
    <input type="text" name="repassword" placeholder="确认密码"> <br>
    <input type="text" name="py" placeholder="拼音码"> <br>
    <input type="text" name="salary" placeholder="工资"> <br>
    <input type="text" name="nativePlaceProvince" placeholder="籍贯省"> <br>
    <input type="text" name="nativePlaceCity" placeholder="市"> <br>
    <input type="text" name="dataOfBirth" placeholder="出生日期"> <br>
    <input type="text" name="enabled" placeholder="可用标记"> <br>
    <input type="button" id="btnOpe" value="保存">
    <input type="button" value="取消" onclick="javascript:history.back(-1);">
</form>

<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>


    $("#btnOpe").click(function () {
        var arr = $("#formOpe").serializeArray();
        var obj={}
        $(arr).each(function (index,item) {
            obj[item.name]=item.value
        })
        var url;
        if(sessionStorage.getItem("id")){
            url='/edit';
        }else{
            url='/add';
        }
        $.ajax({
            url:url,
            type:'post',
            data: JSON.stringify(obj),
            contentType:'application/json', // 传到后端的类型
            dataType:'json',                // 后端返回的类型
            success:function (res) {
                if(res.success){
                    window.location.href="/user/list.jsp"
                }else{
                    alert(res.msg);
                }
            }
        })
    });

    $(function () {
        var id = sessionStorage.getItem("id");
        if(id){
            // 回显
            $.ajax({
                url:'/stuServlet?method=getById',
                type:'get',
                data: "id="+id,
                dataType:'json',                // 反端返回的类型
                success:function (res) {
                    if(res.success){
                        var stu = res.data;
                        $("input[name='id']").val(stu.id);
                        $("input[name='name']").val(stu.name);
                        $("input[name='age']").val(stu.age);
                        $("input[name='gender']").val(stu.gender);
                        $("input[name='address']").val(stu.address);
                        $("input[name='birth']").val(stu.birth);
                    }else{
                        alert(res.msg);
                    }

                }
            })
        }
    })
</script>
</body>
</html>
